#ifndef _URLCODER_H_
#define _URLCODER_H_
#include "std_ex.h"

class UrlCoder
{
public:
	static bool IsBigEndian()
	{
		static bool flag = false;
		static bool bigEndian = false;
		if(!flag)
		{
			union{int a;char b;} uni;
			uni.a = 1;
			bigEndian = (uni.b != 1);
			flag = true;
		}
		return bigEndian;
	}
	static string URLDecode(const string& sIn)
	{
		string sOut;
		const char* p_str = sIn.c_str();
		char* p = (char*)p_str;
		while(*p){
			if(*p == '+')
				sOut.push_back(' ');
			else if(*p == '%')
			{
				++p;
				int first = *p >= 'A' ? *p - 55 : *p - 48 ;
				++p;
				int second = *p >= 'A' ? *p - 55 : *p - 48 ;
				sOut.push_back((unsigned char)(first * 16 + second));
			}
			else
				sOut.push_back(*p);
			++p;
		}
		return sOut;
	}
	static string URLEncode(const string& sIn)
	{
		string sOut;
		
		const char* p_str = sIn.c_str();
		unsigned char* p = (unsigned char*)p_str;
		while(*p)
		{
			char c = (char)(*p);
			if((*p < 127) && isalnum(c))
				sOut.push_back(c);
			else if((*p < 127) && isspace(c))
				sOut.push_back('+');
			else
			{
				sOut.push_back('%');
				sOut.push_back(toHex(*p>>4));
				sOut.push_back(toHex(*p%16));
			}
			++p;
		}
		return sOut;
	}
private:
	static BYTE toHex(const BYTE &x)
	{
		return x > 9 ? x + 55: x + 48;
	}
};
#endif